<?php
define('DEBUG', 'on');
define("WEBPATH", str_replace("\\","/", __DIR__));
require __DIR__ . '/libs/lib_config.php';

class WebSocket extends Swoole\Protocol\WebSocket
{
    protected $message;
    static public $table;

    public function __construct()
    {
        parent::__construct();

        //创建一个swoole_table。存储客户端信息
        $table = new swoole_table(1024);
        $table->column('client_id', swoole_table::TYPE_INT);
        $table->column('userid', swoole_table::TYPE_INT);
        $table->column('username', swoole_table::TYPE_STRING, 20);
        $table->column('avatar', swoole_table::TYPE_STRING, 100);
        $table->create();
        self::$table = $table;

    }

    /**
     * @param     $serv swoole_server
     * @param int $worker_id
     */
    function onStart($serv, $worker_id = 0)
    {
        Swoole::$php->router(array($this, 'router'));
        parent::onStart($serv, $worker_id);
    }

    function router()
    {
        var_dump($this->message);
    }

    /**
     * 进入
     * @param $client_id
     */
    function onEnter($client_id)
    {

    }

    /**
     * 下线时，通知所有人
     */
    function onExit($client_id)
    {
        //获取客户端用户信息
        $userinfo = $this->getClientInfo($client_id);
        if(!$userinfo)
            return ;
        $message_close = array('message_type'=>'logout', 'userid'=>$userinfo['userid'], 'from_client_name'=>$userinfo['username'], 'time'=>date('Y-m-d H:i:s'));
        self::$table->del($userinfo['userid']);
        echo "client {$client_id} closed\n";
        $this->broadcast($client_id, json_encode($message_close));
        //将下线消息发送给所有人
        //$this->log("onOffline: " . $client_id);
        //$this->broadcast($client_id, "onOffline: " . $client_id);
    }

    function getClientInfo($client_id){
        $userinfo = array();
        foreach (self::$table as $_userid => $_info){
            if($_info['client_id'] == $client_id){
                $userid = $_userid;
                $userinfo = $_info;
                break;
            }
        }
        return $userinfo;
    }

    function onMessage_mvc($client_id, $ws)
    {
        $this->log("onMessage: ".$client_id.' = '.$ws['message']);

        $this->message = $ws['message'];
        $response = Swoole::$php->runMVC();

        $this->send($client_id, $response);
        //$this->broadcast($client_id, $ws['message']);
    }

    /**
     * 接收到消息时
     */
    function onMessage($client_id, $ws)
    {
        // 客户端传递的是json数据
        $message_data = json_decode(($ws['message']), true);
        if(!$message_data)
        {
            return ;
        }
		var_dump($ws['message']);
		$this->message = $ws['message'];
        switch($message_data['type'])
        {
            case 'init':
                //用户登录或者注册， 返回userid
                $model_user = model('User');
                $userinfo = $model_user->get($message_data['openid'], 'username')->get();  //暂时把openid保存在username
                
                if($userinfo){
                    $userid = $userinfo['userid'];
                }else{
                    //保存用户信息
                    $input_data['username'] = $message_data['openid'];
                    $input_data['avatar']   = $message_data['avatar'];
                    $input_data['nickname'] = $message_data['nickname'];
                    $input_data['gender']   = $message_data['gender'];
                    $userid = $model_user->put($input_data);
                }
                echo "~~~\n";
                $init_message['message_type']   = 'init';
                $init_message['userid'] = $userid;

                //记录客户端号
                self::$table->set($userid, array('client_id' => $client_id, 'username' => $message_data['nickname'], 'userid' => $userid, 'avatar' => $message_data['avatar']));
                echo "client {$client_id} open\n";
                $this->send($client_id, json_encode($init_message));
                break;
            case 'login':
                $username = htmlspecialchars($message_data['username']);
                $userid = htmlspecialchars($message_data['userid']);
                $avatar = htmlspecialchars($message_data['avatar']);

                //记录客户端号
                //self::$table->set($userid, array('client_id' => $client_id, 'username' => $username, 'userid' => $userid));
                //echo "client {$client_id} open\n";

                // 转播给当前房间的所有客户端，xx进入聊天室
                $login_message = array('message_type'=> 'login', 'client_id' => $client_id, 'username'=>htmlspecialchars($username), 'avatar' => $avatar, 'time'=>date('Y-m-d H:i:s'), 'userid' => $userid);

                $this->broadcast($client_id, json_encode($login_message));

                // 给当前用户发送用户列表
                // 获取所有用户列表 , 除了自己
                $clients_list = array();
                foreach(self::$table as $key => $row){
                    if($row['client_id'] != $client_id)
                        $clients_list[$row['userid']] = $row;
                }
                $login_message['client_list'] = $clients_list;
                $this->send($client_id, json_encode($login_message));

                //提取未读消息
                /*$model_user_message = model('UserMessage');
                $result = $model_user_message->get($userid, 'to_userid');
                $message_list = $result->get();
                if($message_list){
                    //返回未读消息
                }*/

                break;
            case 'chatMessage':
                if(!$message_data['content']){
                    return;
                }
				
                //保存聊天记录到数据库
                $from_user_info = $this->getClientInfo($client_id);
				//机器人聊天
				if($message_data['to_client_id'] == 1){
					$tuling_message = array(
                        'message_type'=>'chatMessage',
					    'type' => 'friend',
                        'id'=> 1,
                        'username' => '晴儿',
                        'avatar' => 'http://tp1.sinaimg.cn/1571889140/180/40030060651/1',
                        'content'=> nl2br(htmlspecialchars($this->getChat($message_data['content']))),
                        'time'=>date('Y-m-d H:i:s'),
                    );

                    $this->send($client_id, json_encode($tuling_message));
					return;
				}
                $to_user_info = self::$table->get($message_data['to_client_id']);

                //保存到数据库
                $insert_data['userid']      = $from_user_info['userid'];
                $insert_data['to_userid']   = $message_data['to_client_id'];
                $insert_data['content']     = $message_data['content'];
                
                $model_user_message = model('UserMessage');
                $result = $model_user_message->put($insert_data);
                var_dump($result);
                
                //如果对方不在线， 则保存到数据库
                if(!$to_user_info){

                    $not_online = array(
                        'type'  => 'not_online',
                    );
                    $this->send($client_id, json_encode($not_online));
                    //
                }else{
                    $new_message = array(
                        'message_type'=>'chatMessage',
                        'type'  => 'friend',
                        'id'=> $from_user_info['userid'],
                        'username' =>$message_data['username'],
                        'avatar' => $message_data['avatar'],
                        'content'=> nl2br(htmlspecialchars($message_data['content'])),
                        'time'=>date('Y-m-d H:i:s'),
                    );

                    $this->send($to_user_info['client_id'], json_encode($new_message));
                }


                break;
			case 'addFirend':
				//添加好友
				//判断是否在线
				break;
        }
        //$this->log("onMessage: ".$client_id.' = '.$ws['message']);
        //$this->send($client_id, 'Server: '.$ws['message']);
    }

    function broadcast($client_id, $msg)
    {
        foreach ($this->connections as $clid => $info)
        {
            if ($client_id != $clid)
            {
                $this->send($clid, $msg);
            }
        }
    }

    function saveMessage(){

    }
	
	//自动回复
	public function getChat($keyword){
		//默认使用图灵机器 
		return $this->getTuling($keyword);
	}
	
	//图灵
	public function getTuling($keyword){
		$url = 'http://www.tuling123.com/openapi/api?key=2e7fd2823e14defb9c903f5ab35e64e4&info='.urlencode($keyword);
		$content = $this->_curl($url);
		if($content['code'] == 100000){
			return $content['text'];
		}
		
		return '我现在还小, 等我长大后再回答你的问题';
		
	}
	public function _curl($url){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$txt = curl_exec($ch);
		if (curl_errno($ch)) {
			return false;
		}
		curl_close($ch);
		return json_decode($txt, true);
	}
}

//require __DIR__'/phar://swoole.phar';
Swoole\Config::$debug = true;
Swoole\Error::$echo_html = false;

$AppSvr = new WebSocket();
$AppSvr->loadSetting(__DIR__."/swoole.ini"); //加载配置文件
$AppSvr->setLogger(new \Swoole\Log\EchoLog(true)); //Logger

/**
 * 如果你没有安装swoole扩展，这里还可选择
 * BlockTCP 阻塞的TCP，支持windows平台
 * SelectTCP 使用select做事件循环，支持windows平台
 * EventTCP 使用libevent，需要安装libevent扩展
 */
$enable_ssl = false;
$server = Swoole\Network\Server::autoCreate('0.0.0.0', 9510, $enable_ssl);
$server->setProtocol($AppSvr);
//$server->daemonize(); //作为守护进程
$server->run(array(
    'worker_num' => 1,
    //'ssl_key_file' => __DIR__.'/ssl/ssl.key',
    //'ssl_cert_file' => __DIR__.'/ssl/ssl.crt',
    //'max_request' => 1000,
    //'ipc_mode' => 2,
    //'heartbeat_check_interval' => 40,
    //'heartbeat_idle_time' => 60,
));
